<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="销售价方案" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model="model.name" placeholder="请输入销售价方案" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
              <a-form-model-item label="生效时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="effectBeginTime" v-if="title_ === '新增'">
                <j-date placeholder="请选择生效时间"  v-model="model.effectBeginTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" :disabled-date="disabledDate" :disabled-time="disabledTime" />
              </a-form-model-item>
              <a-form-model-item label="生效时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="effectBeginTime" v-else>
                <j-date placeholder="请选择生效时间"  v-model="model.effectBeginTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" :disabled-date="disabledDate" :disabled-time="disabledTime" />
              </a-form-model-item>
            </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="公斤费" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="kiloFee">
              <a-input-number v-model="model.kiloFee" placeholder="请输入公斤费" :min="0" :precision="3" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="处理费" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="processFee">
              <a-input-number v-model="model.processFee" placeholder="请输入处理费" :min="0" :precision="3" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-tabs type="card" v-model="activeKey" :class="{tabDisabled: formDisabled}">
          <a-tab-pane key="1" tab="选择成本价方案">
            <cost-plan v-model="model.costPriceCodes" v-bind="modalProps" />
          </a-tab-pane>
          <a-tab-pane key="2" tab="选择客户">
            <!-- 编辑禁止操作 -->
            <cost-plan v-model="model.departIds" v-bind="modalProps_" :class="{editDisabled: title_ === '编辑'}" />
          </a-tab-pane>
        </a-tabs>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction, postFormAction } from '@/api/manage'
  import costPlan from './costPlan'
  import moment from 'moment'

  export default {
    name: 'LogisticsSalesPriceForm',
    mixins:[],
    components: {
      costPlan
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      title_: {
        type: String,
        default: ''
      }
    },
    data () {
      return {
        model:{},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          name: [
            { required: true, message: '请输入销售价方案名称!'},
          ],
          kiloFee: [
            { required: true, message: '请输入公斤费!'},
          ],
          processFee: [
            { required: true, message: '请输入处理费!'},
          ],
          effectBeginTime: [
            { required: true, message: '请选择生效时间!' },
            { validator: this.validEffectBeginTime }
          ]
        },
        url: {
          add: "/logistics/sales/logisticsSalesPrice/add",
          edit: "/logistics/sales/logisticsSalesPrice/edit",
          queryById: "/logistics/sales/logisticsSalesPrice/queryById",
          queryLatestVersion: '/logistics/sales/logisticsSalesPrice/queryLatestVersion',
          list: "/logistics/sales/logisticsSalesPrice/queryVersionList",
          delete: "/logistics/sales/logisticsSalesPrice/delete",
          assignDepart: "/logistics/sales/logisticsSalesPrice/assignDepart"
        },
        activeKey: '1',
        modalProps: {
          modalPropsCustom: true,
          columns: [
            {
              align: "center",
              dataIndex: "name",
              title: "成本价方案",
              width: "50%",
              isShow: true
            },
            {
              align: "center",
              dataIndex: "channelName",
              title: "渠道名称",
              width: "50%",
              isShow: true
            }
          ],
          listUrl: "/logistics/costPrice/logisticsCostPrice/list",
          multiple: true,
          rowKey: 'code',
          valueKey: 'codes',
          queryParamConfig: {
            ableStatus: '2', //可以正常使用的
          },
          queryConfig: [
            {key: 'name', label: '成本价方案'},
            {key: 'channelId', label: '渠道名称', dictCode: "hz_logistics_channel,channel_name,id,logistics,is_enable='Y'"},
          ]
        },
        modalProps_: {
          modalPropsCustom: true, //自定义，区分已有业务
          columns: [
            {
              align: "center",
              dataIndex: "departName",
              title: "客户名称",
              width: "25%",
              isShow: true //是否在已选中中显示
            },
            {
              align: "center",
              dataIndex: "orgCode",
              title: "客户ID",
              width: "25%",
              isShow: true //是否在已选中中显示
            },
            {
              align: "center",
              dataIndex: "departLevel_dictText",
              title: "客户级别",
              width: "25%",
              isShow: true //是否在已选中中显示
            },
            {
              align: "center",
              dataIndex: "groupId_dictText",
              title: "客户分组",
              width: "25%",
              isShow: true //是否在已选中中显示
            }
          ],
          listUrl: "/sys/sysDepart/list",
          multiple: true,
          queryParamConfig: {},
          queryConfig: [
            {key: 'departName', label: '客户名称'},
            {key: 'departLevel', label: '客户级别', dictCode: 'merchant_level'},
            {key: 'groupId', label: '客户分组', dictCode: 'hz_sys_merchant_group,name,id,system'},
          ]
        },
        lastTime: moment(),
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'生效时间',
            align:"center",
            dataIndex: 'effectBeginTime',
            scopedSlots: { customRender: 'timeSlot' }
          },
          {
            title:'状态',
            align:"center",
            dataIndex: 'effectStatus_dictText'
          },
          {
            title:'创建时间',
            align:"center",
            dataIndex: 'createTime'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
      }
    },
    computed: {
      formDisabled() {
        return this.disabled
      },
    },
    created () {
      //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        this.model = Object.assign({}, record);
        this.visible = true;
        // 编辑、历史价格
        if(this.model.id){
          //获取最新版本详情
          this.getQueryLatestVersion();
        }
      },
      getQueryLatestVersion(){
        getAction(this.url.queryLatestVersion, { code: this.model.code }).then((res) => {
          if(res.success){
            let lastTime = res.result && res.result.effectBeginTime;
            // 如果最新版本晚于当前时间，则取最新版版本(下一秒)为校验时间
            if(moment(moment(lastTime).format('YYYY-MM-DD HH:mm:ss')).isAfter(moment(moment().format('YYYY-MM-DD HH:mm:ss')))){
              lastTime = moment(lastTime).add(1, 'seconds');
              this.lastTime = lastTime;
            }
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        that.$refs.form.validate(valid => {
          if (valid) {
            let params = Object.assign({}, that.model);
            // 成本价方案
            if(!params.costPriceCodes){
              that.$message.warning('请选择成本价方案');
              return;
            }

            // 客户
            if(!params.departIds){
              that.$message.warning('请选择客户');
              return;
            }

            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!that.model.id){
              httpurl+=that.url.add;
              method = 'post';
            }else{ 
              httpurl+=that.url.edit;
              method = 'put';
            }
            httpAction(httpurl,params,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
        })
      },
      disabledDate(current){
        // 禁用今天之前的日期
        return current && current < moment(this.lastTime).subtract(1, 'days').endOf('day');
      },
      disabledTime(current){
        let hourList = Array.from({ length: 24 }, (_, index) => index);
        let minutesList = Array.from({ length: 60 }, (_, index) => index);
        let secondsList = Array.from({ length: 60 }, (_, index) => index);
        // 1.选择时间晚于当前(天)
        if(moment(moment(current).format('YYYY-MM-DD')).isAfter(moment(moment(this.lastTime).format('YYYY-MM-DD')))){
          return {
            disabledHours: () => [],
            disabledMinutes: () => [],
            disabledSeconds: () => [],
          };
        }else if(moment(moment(current).format('YYYY-MM-DD')).isBefore(moment(moment(this.lastTime).format('YYYY-MM-DD')))){
          //3.编辑返参早于当前
          return {
            disabledHours: () => hourList,
            disabledMinutes: () => minutesList,
            disabledSeconds: () => secondsList,
          };
        }
        // 2.选择时间等于当前(天)
        let currentHourList = [], currentminutesList = [], currentsecondsList = [];
        if(moment(current).format('YYYY-MM-DD') === moment(this.lastTime).format('YYYY-MM-DD')){
          // 选择的时间为限制时间之后
          currentHourList = hourList.filter(item => item < moment(this.lastTime).format('HH'));
          // 2.选择时间等于当前(时)
          if(moment(current).format('YYYY-MM-DD HH') === moment(this.lastTime).format('YYYY-MM-DD HH')){
            // 选择的时间为限制时间之后
            currentminutesList = minutesList.filter(item => item < moment(this.lastTime).format('mm'));
            // 2.选择时间等于当前(分)
            if(moment(current).format('YYYY-MM-DD HH:mm') === moment(this.lastTime).format('YYYY-MM-DD HH:mm')){
              currentsecondsList = secondsList.filter(item => item < moment(this.lastTime).format('ss'));
            }else if(moment(moment(current).format('YYYY-MM-DD HH:mm')).isAfter(moment(moment(this.lastTime).format('YYYY-MM-DD HH:mm')))){
              // 选择时间晚于当前(分)
              currentsecondsList = [];
            }else if(moment(moment(current).format('YYYY-MM-DD HH:mm')).isBefore(moment(moment(this.lastTime).format('YYYY-MM-DD HH:mm')))){
              // 选择时间早于当前(分)
              currentsecondsList = secondsList;
            }
          }else if(moment(moment(current).format('YYYY-MM-DD HH')).isAfter(moment(moment(this.lastTime).format('YYYY-MM-DD HH')))){
            // 选择时间晚于当前(时)
            currentminutesList = [];
            currentsecondsList = [];
          }else if(moment(moment(current).format('YYYY-MM-DD HH')).isBefore(moment(moment(this.lastTime).format('YYYY-MM-DD HH')))){
            // 选择时间早于当前(时)
            currentminutesList = minutesList;
            currentsecondsList = secondsList;
          }
          return {
            disabledHours: () => currentHourList,
            disabledMinutes: () => currentminutesList,
            disabledSeconds: () => currentsecondsList,
          };
        }
      },
      validEffectBeginTime(rule, value, callback){
        if(!value){
          callback('请选择生效时间!');
        }else{
          if(moment(moment(value).format('YYYY-MM-DD HH:mm:ss')).isBefore(moment(moment(this.lastTime).format('YYYY-MM-DD HH:mm:ss')))){
            callback('生效时间需晚于最新版本时间或系统时间!');
          }else{
            callback();
          }
        }
      }
    }
  }
</script>

<style scoped lang="less">
.ant-checkbox-wrapper{
  height: 40px;
  line-height: 40px;
}
/deep/.ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-tab-active{
  border-color: #1890FF;
  border-bottom: 1px solid #fff;
  background: rgba(24,144,255, 0.1);
}
/deep/.ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-tab{
  border-color: #1890FF;
  border-bottom: 1px solid #fff;
  color: #1890FF;
}
.editDisabled{
  /deep/.ant-form{
    cursor: not-allowed;
    &>div, &>button, &>a{
      -ms-pointer-events: none;
      pointer-events: none;
    }
  }
  /deep/.ant-table table{
    cursor: not-allowed;
    tbody, thead{
      -ms-pointer-events: none;
      pointer-events: none;
    }
  }
}
.tabDisabled{
  cursor: auto;
  pointer-events: auto;
  /deep/.ant-form{
    cursor: not-allowed;
    &>div, &>button, &>a{
      -ms-pointer-events: none;
      pointer-events: none;
    }
  }
  /deep/.ant-table table{
    cursor: not-allowed;
    tbody, thead{
      -ms-pointer-events: none;
      pointer-events: none;
    }
  }
}
</style>